<template>
  <el-form-item label="字体大小">
    <el-radio-group v-model="editorForm.fontSize.isDefault" @change="handleDefault">
      <el-radio :label="true">默认</el-radio>
      <el-radio :label="false">自定义</el-radio>
    </el-radio-group>
    <div v-if="!editorForm.fontSize.isDefault" class="custom-after">
      <el-select v-model="editorForm.fontSize.pxValue" placeholder="选择字号" style="width: 90px" allow-create filterable default-first-option @change="getRealValue">
        <el-option v-for="item in sizeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
  </el-form-item>
</template>

<script setup>
import { inject, ref, onMounted } from 'vue'
import { pxToRem } from '@/utils/tools'

const { editorForm, domList, changeDefault, backUpdate, updateGlobalProp } = inject('commonForm')
// 初始化属性和元素对应关系
const bindDom = ref([])
const initDomMapping = () => {
  const bindKeys = [`${editorForm.value._key}.fontSize.value`]
  domList.value.forEach(element => {
    const bindValue = element.getAttribute('_bind')
    bindKeys.forEach(key => {
      if (bindValue.includes(key)) {
        bindDom.value.push(element)
      }
    })
  })
}

const handleDefault = (val) => {
  if (val) {
    changeDefault('fontSize')
  }
  bindDom.value.forEach(element => {
    element.style.fontSize = editorForm.value.fontSize.value
  })
  if (bindDom.value.length === 0) {
    backUpdate()
  }
}

const getRealValue = () => {
  if (typeof(editorForm.value.fontSize.pxValue) === 'number') {
    editorForm.value.fontSize.value = pxToRem(editorForm.value.fontSize.pxValue)
  } else {
    const pxValue = editorForm.value.fontSize.pxValue.split('px')[0]
    if (!pxValue) return
    editorForm.value.fontSize.value = pxToRem(pxValue)
  }
  if (editorForm.value.fontSize.globalId) {
    const prop = { fontSize: editorForm.value.fontSize }
    updateGlobalProp(editorForm.value.fontSize.globalId, prop)
    return
  }
  bindDom.value.forEach(element => {
    element.style.fontSize = editorForm.value.fontSize.value
  })
  if (bindDom.value.length === 0) {
    backUpdate()
  }
}

const sizeOptions = ref([
  { label: '12px', value: 12 },
  { label: '14px', value: 14 },
  { label: '16px', value: 16 },
  { label: '18px', value: 18 },
  { label: '20px', value: 20 },
  { label: '22px', value: 22 },
  { label: '24px', value: 24 },
  { label: '30px', value: 30 },
  { label: '36px', value: 36 },
  { label: '40px', value: 40 },
  { label: '48px', value: 48 },
  { label: '60px', value: 60 },
  { label: '72px', value: 72 },
  { label: '84px', value: 84 },
  { label: '96px', value: 96 },
  { label: '108px', value: 108 },
  { label: '120px', value: 120 }
])

onMounted(() => {
  initDomMapping()
})
</script>

<style lang="scss" scoped>

</style> 